<?php
/*
 * @Author: ZhaohangYang <yangzhaohang@comsenz-service.com>
 * @Date: 2021-06-23 16:58:47
 * @Description: 伙伴智慧大客户研发部
 */
namespace App\ModelsHuoban;

use Swoole\Coroutine;
use Swoole\Coroutine\WaitGroup;

abstract class HuobanActionMapping
{
    public static $tableId       = '';
    public static $tableAlias    = '';
    public static $preTableAlias = '';
    // 映射请求并发
    public static $mappingBasicConcurrent = 20;
    // 映射请求limit
    public static $mappingBasicLimit = 500;

    public static function mappingBasic($mappingBasicCallbacks, $body = [])
    {
        $total = HuobanBasic::huobanItem()->getTotal(static::$tableId, $body);

        $page_size  = static::$mappingBasicLimit;
        $page_total = ceil($total / $page_size);

        $page_total_arr = range(0, $page_total);
        $page_blocks    = array_chunk($page_total_arr, static::$mappingBasicConcurrent);

        foreach ($page_blocks as $page_block) {

            $wg = new WaitGroup();
            foreach ($page_block as $page) {
                $wg->add();
                Coroutine::create(function () use ($page, $page_size, $mappingBasicCallbacks, $wg) {
                    $body = [
                        'offset' => $page * $page_size,
                        'limit'  => $page_size,
                    ];
                    $response = HuobanBasic::huobanItem()->findFormatItems(static::$tableId, $body);
                    foreach ($mappingBasicCallbacks as $mappingBasicCallback) {
                        forward_static_call_array([static::class, $mappingBasicCallback], [$response]);
                    }
                    print_r(static::$preTableAlias . ':page-' . $page . '已完成' . PHP_EOL);
                    $wg->done();
                });
            }

            $wg->wait();
        }
    }
}
